import { fetchList, add, edit, del } from '@/services/coupon/CouponInfo';
import { message } from 'antd';

export default {
  namespace: 'POperationCoupon',

  state: {
    dataTable: {
      total: 0,
      list: [],
    },
  },

  effects: {
    * fetchList({ payload }, { call, put }) {
      const response = yield call(fetchList, payload);
      if (response.code === 0) {
        let dataTable = response.data;
        dataTable.list = dataTable.list.map(d => {
          d.mchCount = d.couponMchLinkList ? d.couponMchLinkList.length : 0;
          d.issueMchCount = d.issueCouponMchLinkList ? d.issueCouponMchLinkList.length : 0;
          d.periodTime = d.startTime && d.endTime ? `${d.startTime.substring(0, 10)}至${d.endTime.substring(0, 10)}` : '-';
          return d;
        });
        yield put({
          type: 'chgDataTable',
          payload: dataTable,
        });
      }
    },

    * add({ payload, callback }, { call }) {
      const response = yield call(add, payload);
      if (response.code === 0) {
        message.success('添加成功').then();
        callback && callback();
      }
    },

    * edit({ payload, callback }, { call }) {
      const response = yield call(edit, payload);
      if (response.code === 0) {
        message.success('修改成功').then();
        callback && callback();
      }
    },

    * del({ payload, callback }, { call }) {
      const response = yield call(del, payload);
      if (response.code === 0) {
        message.success('删除成功').then();
        callback && callback();
      }
    },

  },

  reducers: {
    chgDataTable(state, action) {
      return {
        ...state,
        dataTable: action.payload,
      };
    },
  },
};
